#ifndef _THREAD_HPP_
#define _THREAD_HPP_

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <functional>

namespace Thread
{
using func_t = std::function<void()>;

//typedef void* (*func_t)(void*) ;

class Task
{
    public: 
        Task(func_t f)
            :_f(f)
        {
            ;
        }
        ~Task()
        {}

        func_t Ptr()
        {
            return _f;
        }
    private:
        func_t _f;
};

// int i = 0;

//template < class T >
class Thread
{
    private:
    void EnableDeatach()
    {
        _IsDetach = true;
    }
    void EnableRunning()
    {
        _IsRunning = true;
    }
    public:
    
    // 初始化函数和传参。
    Thread(func_t t)
        :_t(t)
        ,_IsRunning(false)
        ,_IsDetach(false)
    {
        std::cout << "创建Thread" << std::endl;
    }

    ~Thread()
    {
        // 当该线程没被取消时，

        //++i;
        //std::cout << "析构Thread" << std::endl;
        //std::cout << i << std::endl;

        if(_IsRunning == true)
        {
            //Cancel();
            Join();
        }
    }

    static void *Rountine(void* argv)
    {
        Thread* self = static_cast<Thread*>(argv);

        self->_t();
        
        return nullptr;
    }
    

    void SwapDitach()
    {
        if(_IsDetach == true)
        {
            return ;
        }

        int n = pthread_detach(_pt);

        if(n == 0)
        {
            EnableDeatach();
            //std::cout << "分离成功！" << std::endl;
        }
        else
        {
            std::cout << "分离失败！" << std::endl;
        }
    }

    // 开始执行对应的线程。
    void Start()
    {
        if(_IsRunning)
        {
            return ;
        }

        int ret = pthread_create(&_pt,nullptr,Rountine,this);

        if(ret == 0)
        {
            EnableRunning();
            //std::cout << "成功创建线程" << std::endl;
        }
        else
        {
            std::cerr << "创建线程失败" << std::endl;;
            exit(1);
        }
    }

    // 取消对应的线程。
    void Cancel()
    {
        int n = pthread_cancel(_pt);

        if(n == 0)
        {
            _IsRunning = false;
            //std::cout << "取消线程" << std::endl;
        }
        else
        {
            std::cout << "取消线程失败" << std::endl;
        }
    }

    void Join()
    {
        if(_IsDetach == true)
        {
            return ;
        }

        int n = pthread_join(_pt,nullptr);

        if(n == 0)
        {
            std::cout << "等待成功！" << std::endl;
        }
        else
        {
            std::cout << "等待失败！" << std::endl;
        }
    }

    private:
        pthread_t _pt;
        func_t _t;
        bool _IsRunning;
        bool _IsDetach;
};
}

#endif